package org.javarosa.communication.http.mesh4j.extensions;

import java.util.Vector;

import org.javarosa.communication.http.HttpTransportDestination;
import org.javarosa.communication.http.HttpTransportProperties;
import org.javarosa.communication.http.ui.HttpDestinationRetrievalActivity;
import org.javarosa.core.JavaRosaServiceProvider;
import org.javarosa.core.api.IActivity;
import org.javarosa.core.services.ITransportManager;
import org.javarosa.core.services.mesh4j.extensions.SyncEngineService;
import org.javarosa.core.services.transport.ITransportDestination;
import org.javarosa.core.services.transport.TransportMessage;
import org.javarosa.core.services.transport.TransportMethod;
import org.javarosa.xform.mesh4j.extensions.FormDefUtils;

public class Mesh4jHttpTransportMethod implements TransportMethod {

	private final static String NAME = "HTTP";
	
	// MODEL VARIABLES
	private TransportMessage message;
	private ITransportManager manager;
	private IActivity retrievalActivity;
	
	private Thread worker; 

	// BUSINESS METHODS
	
	public int getId() {
		return TransportMethod.HTTP_GCF;
	}

	public String getName() {
		return NAME;
	}

	public void transmit(TransportMessage message, ITransportManager manager) {
		this.message = message;
		this.manager = manager;
		worker = new Thread(new WorkerThread());
		worker.start();
		//sendData();
	}

	private class WorkerThread implements Runnable {
		public void run() {
			sendData();
		}
	}
	
	private void sendData() {
		try{
			synchronizeItems();
			// update status
			message.setStatus(TransportMessage.STATUS_DELIVERED);
			message.setChanged();
			message.notifyObservers(null);
		} catch (Throwable e) {
			e.printStackTrace();
			
			// update status
            message.setStatus(TransportMessage.STATUS_FAILED);
            message.setChanged();
            message.notifyObservers(null); 
	    }
	}
	
	
	private void synchronizeItems() {
		// TODO (JMT) Use a OneWay sync strategy to emulate only the send		
		
		int dataModelID = this.message.getModelId();
		String formName = FormDefUtils.getFormNameFromDataModelTreeID(dataModelID);
		Vector conflicts = SyncEngineService.synchronizeItemsSynchronousHttpMethod(formName);		
		
		if(!conflicts.isEmpty()){
			message.setReplyloadData("Error in sync - Conflicts !!!".getBytes());
		} 
	}

	public void closeConnections() {
		//TODO: What should close here?
	}

	public ITransportDestination getDefaultDestination() {
		String url = JavaRosaServiceProvider.instance().getPropertyManager().getSingularProperty(HttpTransportProperties.POST_URL_PROPERTY);
		if(url == null) {
			return null;
		} else {
			return new HttpTransportDestination(url);
		}
	}

	public IActivity getDestinationRetrievalActivity() {
		return retrievalActivity;
	}

	public void setDestinationRetrievalActivity(IActivity activity) {
		retrievalActivity = activity;
	}
}
